import { HttpGet } from "@/network/servers";
import { useEffect, useRef } from "react";
import {
    getBrowserController,
    getNet,
    getWxSDKParams
} from '@/pages/components/utils';
import Taro from '@tarojs/taro'
import md5 from 'md5';
import qs from 'qs';
import Utils from "./index";
import dayjs from 'dayjs';
import _ from 'lodash'
import toObject from 'dayjs/plugin/toObject';
import objectSupport from 'dayjs/plugin/objectSupport';
import { getBaseUrl } from "@/network/baseUrl";

let wx = require('weixin-js-sdk')
const browserController = getBrowserController()
const net = getNet()

/**
 * 设置文档页面title
 * @param title 当前页面的标题
 * @param onPageUnmount 返回上一页同时还原之前的标题
 */
export const useDocumentTitle = (title: string, onPageUnmount: boolean = true) => {
    let oldTitle = useRef(document.title).current

    useEffect(() => {
        document.title = title
    }, [title])

    useEffect(() => {
        return () => {
            if (!onPageUnmount) {
                document.title = oldTitle
                window.refreshPage && typeof window.refreshPage === 'function' && window.refreshPage()
            }
        }
    }, [])

}

/**
 * 获取系统accessToken
 * @param sysId 系统地址
 * @returns accessToken
 */
export const getAccessToken = (sysId: string) => {
    return md5(sysId).split('').reverse().join('')
}

/**
 * 获取用户身份信息
 * @param baseAddr 基础平台地址
 * @param sysId 系统地址 默认使用基础平台
 * @param token 用户token
 * @returns userInfo 用户信息
 */
export const useGetUserInfo = async (baseAddr: string, sysId: string = '000', token: string) => {
    let result = await HttpGet({
        url: baseAddr + '/BaseApi/Login/GetOnlineUserInfo',
        data: {
            appid: sysId,
            access_token: getAccessToken(sysId),
            token
        },
        load: true
    })

    let userInfo = result.Data
    return userInfo
}

/**
 * 向url上添加参数
 * @param url 需要转换参数的url
 * @param params 添加的参数对象
 * @returns newUrl 添加上参数的新url
 */
export const useTransformUrl = (url: string, params: object) => {
    if (url.indexOf('schoolId') > -1 && url.indexOf('env') > -1) {  //已经携带schoolId，不再处理
        return url
    }
    let paramList = url.split('#')
    let newUrl = ''
    if (Array.isArray(paramList) && paramList.length > 0) {
        for (let i = 0; i < paramList.length; i++) {
            let item = paramList[i]
            if (i == 0) {
                item += `&${qs.stringify(params)}`
            }
            newUrl += item + '#'
        }
    }

    return newUrl
}

/**
 * 获取文件名不带后缀
 * @param fileName 文件名
 * @returns 
 */
export const useGetFileName = (fileName: string) => {
    if (!fileName) {
        return '文件'
    }

    let pot1 = fileName.lastIndexOf('.')
    return fileName.substring(0, pot1)
}


/**
 * 上传文件
 * @param url 文件下载地址
 * @param fileName 文件名
 * @param file 文件
 * 
 */
export const useDownloadFile = (url: string, fileName: string, file: any) => {
    let name = useGetFileName(fileName)
    return new Promise(async (resolve, reject) => {
        if (Utils.getSystemInfo() === 'weapp') {
            const params = await getWxSDKParams([])
            wx.config(params);
            try {
                browserController.openFileForWebview(wx, { fileUrl: url, fileName: name })
            } catch (error) {
                Taro.showToast({ title: error, icon: 'none' })
            }
        } else {
            net.downloadFile({
                url,
                fileName,
                onProgress: process => {
                    Taro.showToast({
                        icon: 'loading',
                        title: `正在下载${process}`
                    })
                },
                onSuccess: path => {
                    Taro.showToast({
                        title: '下载成功',
                        icon: 'success',
                        duration: 2000
                    })
                    resolve(path)
                },
                onError: error => {
                    Taro.showToast({
                        title: '下载失败',
                        icon: 'none',
                        duration: 2000
                    })
                    reject(error)
                }
            })
        }
    })
}

//获取当前tab背景
export const useGetTabBg = () => {
    if (Utils.getSystemInfo() === 'weapp') {
        return {
            background: '#00a2ff'
        }
    } else {
        return {}
    }
}

/**
 * 将时间格式化为xx分钟前 xx小时前
 * @param date 时间
 * @returns updateDate 格式化的时间
 */
export const useResetDate = (date: string) => {
    dayjs.extend(objectSupport)
    dayjs.extend(toObject)

    if (!dayjs(date).isValid()) {
        return
    }

    let updateDate = ''

    let nowTimeObj = dayjs().toObject();
    let afferentTimeObj = dayjs(date).toObject()

    if (afferentTimeObj['years'] == nowTimeObj['years'] && afferentTimeObj['months'] == nowTimeObj['months'] && afferentTimeObj['date'] == nowTimeObj['date']) {
        let diffHour = nowTimeObj['hours'] - afferentTimeObj['hours']
        let diffminus = nowTimeObj['minutes'] - afferentTimeObj['minutes']
        if ((diffminus == 0 && diffHour == 0) || diffHour < 0) {
            updateDate = '刚刚'
        } else if (diffHour > 0) {
            updateDate = `${diffHour}小时前`
        } else {
            if (diffminus < 0) {
                updateDate = '刚刚'
            } else {
                updateDate = `${diffminus}分钟前`
            }
        }

    } else {
        updateDate = dayjs(afferentTimeObj).format('YYYY-MM-DD')
    }

    return updateDate;
}

/**
 * 手动限制字符串长度
 * @param title 传入的标题字符串
 * @param num 限制长度
 * @returns 处理好的标题
 */
export const useTitleCut = (title: string, num: number = 35) => {
    if (title.length > num) {
        return `${title.substring(0, num)}...`
    } else {
        return title
    }
}

/**
 * 深拷贝
 * @param objects 需要拷贝的数据
 * @returns 深克隆的数据
 */
export const useDeepClone = (objects) => {
    let deep = _.cloneDeep(objects)

    return deep
}

/**
 * 判断当前是否为数组类型，且不为空
 * @param arr 需要判断为数组的数据
 * @returns boolean 
 */
export const useGetIsMapArray = (arr) => {
    return _.isArray(arr) && arr.length > 0
}
/**
 * 在线检测方法
 * @param url 基础平台地址
 * @param token 用户token
 * @param sysId 当前系统id
 * @param callback 回调函数
 */
export const useOnlineCheck = (url, token, sysId, callback?) => {
    if (Utils.getSystemInfo() === 'h5') { //只有在app时才调用
        const script = document.createElement('script')
        script.setAttribute('src', `${url}/JS/mobile-check-online.min.js`)
        document.head.appendChild(script)
        script.addEventListener('load', () => {
            window.lgCheckOnline(url, token, sysId, callback)
        })
    }
}

/**
 * 测试环境获取mock地址
 * @returns mock地址
 */
export const useMockAddr = () => {
    if (process.env.NODE_ENV === 'development') {
        return 'http://127.0.0.1:4523/m1/2577150-0-default'
    } else {
        return ''
    }
}

/**
 * 从富文本中提取图片地址数组
 * @param content 富文本内容
 * @returns url数组
 */
export const useGetImgInRichText = (content) => {
    if (!content) {
        return
    }
    let imgs = content.match(/<img[^>]+>/g);
    if (!imgs) {
        return
    }
    let arrImg: any = []
    for (let j = 0; j < imgs.length; j++) {
        imgs[j].replace(/<img[^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
            capture = useGetOutsideUrl(capture, '/upload/', getBaseUrl())
            arrImg.push(capture)
        })
    }
    return arrImg
}

/**
 * 小程序下将内网资源地址拼接为外网
 * @param url 原始url
 * @param splitParams 用于分割url的参数
 * @param outsizeUrl 外网地址
 * @returns 外网url
 */
export const useGetOutsideUrl = (url, splitParams, outsizeUrl) => {
    if (Utils.getSystemInfo() === 'h5' || !url.includes(splitParams) || !outsizeUrl || url.includes('https://')) {
        return url
    }

    let newUrl = outsizeUrl + splitParams + url.split(splitParams)[1]

    return newUrl
}







